package pluginMain;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import com.comphenix.protocol.utility.StreamSerializer;

public class DRIUtils
{
	static boolean createTable()
	{
		if (DRISQL.openConnect()) {
			Statement statement;
			if (DRIMain.plugin.getConfig().getBoolean("config.usemysql")) {
				try {
					statement = DRISQL.connection.createStatement();
					String sql = "CREATE TABLE IF NOT EXISTS DRItems (Id INT NOT NULL AUTO_INCREMENT, "
							+ "Player TEXT, Level INT, Items TEXT, Time INT, PRIMARY KEY (Id));";
					statement.executeUpdate(sql);
					sql = "CREATE TABLE IF NOT EXISTS DRItemsGroup ("
							+ "Group TEXT, Items TEXT);";
					statement.executeUpdate(sql);
					statement.close();
					return true;
				}
				catch (SQLException e) {
					e.printStackTrace();
					return false;
				}
			}
			else {
				try {

					statement = DRISQL.connection.createStatement();
					String sql = "CREATE TABLE IF NOT EXISTS DRItems (Id INTEGER PRIMARY KEY AUTOINCREMENT, "
							+ "Player TEXT, Level INTEGER, Items TEXT, Time INTEGER);";
					statement.executeUpdate(sql);
					statement.close();
					return true;
				}
				catch (SQLException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return false;
	}

	private static String createItemsData(Inventory inventory)
	{
		ItemStack[] itemStacks = inventory.getContents();
		StringBuilder stringBuilder = new StringBuilder();
		for (ItemStack itemStack : itemStacks) {
			if (itemStack != null) {
				try {
					stringBuilder.append(StreamSerializer.getDefault().serializeItemStack(itemStack));
				}
				catch (IOException e) {
					e.printStackTrace();
				}
				stringBuilder.append(";");
			}
		}
		return stringBuilder.toString();

	}

	private static String getItemsData(String name, int level)
	{
		String sql;
		String itemsData;
		Statement statement;
		if (level > 1) {
			sql = "SELECT Items FROM DRItems WHERE Player = '" + name + "';";
		}
		else {
			sql = "SELECT Items FROM DRItems WHERE Level = " + level + ";";
		}
		try {
			statement = DRISQL.connection.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			if (resultSet.next()) {
				itemsData = resultSet.getString(1);
				resultSet.close();
				statement.close();
				return itemsData;
			}
			else {
				if (level > 1) {
					sql = "INSERT INTO DRItems (Player) VALUES ('" + name + "');";
				}
				else {
					sql = "INSERT INTO DRItems (Level) VALUES (" + level + ");";
				}
				statement.executeUpdate(sql);
				statement.close();
				return null;
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	static double getTime(Player player)
	{
		int outTime = DRIMain.plugin.getConfig().getInt("config.timeout");
		int playerTime = DRIMain.plugin.getConfig().getInt("player." + player.getName().toLowerCase() + ".time");
		double currentTime = Math.floor(System.currentTimeMillis() / 3600000);
		return (outTime - currentTime + playerTime);
	}

	public static boolean getPlayerTime(Player player)
	{
		int time = 0;
	
		String sql;
		sql = "SELECT Time FROM DRItems WHERE Player = '" + player.getName().toLowerCase() + "';";
		try {
			Statement statement = DRISQL.connection.createStatement();
			ResultSet resultSet = statement.executeQuery(sql);
			if (resultSet.next()) {
				time = resultSet.getInt(1);
				resultSet.close();
				statement.close();
			}
			else {
				sql = "INSERT INTO DRItems (Player, Time) VALUES ('" + player.getName().toLowerCase() + "', 0);";
				statement.executeUpdate(sql);
				statement.close();
			}
			DRIMain.plugin.getConfig().set("player." + player.getName().toLowerCase() + ".time", time);
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}

	private static int getPlayerLevel(Player player)
	{
		int level;
		if (player.hasPermission("dri.use.svip")) {
			level = 2;
		}
		else if (player.hasPermission("dri.use.vip")) {
			level = 1;
		}
		else {
			level = 0;
		}
		return level;
	}

	static Inventory getInventory(String[] args)
	{
		if (args.length < 1) {
			return null;
		}
		String itemsData;
		String[] itemDatas;
		Inventory inventory;
		if (args[0].equalsIgnoreCase("set")) {
			inventory = DRIMain.plugin.getServer().createInventory(null, 27, "DRItems~Common");
			itemsData = getItemsData(null, 0);
		}
		else if (args[0].equalsIgnoreCase("setvip")) {
			inventory = DRIMain.plugin.getServer().createInventory(null, 27, "DRItems~VIP" + args[1]);
			itemsData = getItemsData(null, 1);
		}
		else if (args[0].equalsIgnoreCase("setgroup")) {
			inventory = DRIMain.plugin.getServer().createInventory(null, 27, "Remilia~Group~" + args[1]);
			itemsData = getItemsData(null, 1);
		}
		else if (args[0].equalsIgnoreCase("setplayer")) {
			if (args.length < 2) {
				return null;
			}
			inventory = DRIMain.plugin.getServer().createInventory(null, 27, "DRItems~SVIP~" + args[1].toLowerCase());
			itemsData = getItemsData(args[1].toLowerCase(), 2);
		}
		else {
			itemsData = null;
			return null;
		}
		if (itemsData != null) {
			itemDatas = itemsData.split(";");
			for (String string : itemDatas) {
				if (string.equals("")) {
					continue;
				}
				try {
					inventory.addItem(StreamSerializer.getDefault().deserializeItemStack(string));
				}
				catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return inventory;
	}

	private static boolean setPlayerTime(Player player)
	{
		double time = Math.floor(System.currentTimeMillis() / 3600000);
		String name = player.getName().toLowerCase();
		String sql = "UPDATE DRItems SET Time = " + time + " WHERE Player = '" + name + "';";
		try {
			Statement statement = DRISQL.connection.createStatement();
			statement.executeUpdate(sql);
			statement.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		DRIMain.plugin.getConfig().set("player." + player.getName().toLowerCase() + ".time", time);
		return true;
	}

	static boolean setPlayerItems(Player player)
	{
		String itemsData;
		String[] itemData;
		int level = getPlayerLevel(player);
		itemsData = getItemsData(player.getName().toLowerCase(), level);
		if (itemsData != null) {
			itemData = itemsData.split(";");
			for (String string : itemData) {
				if (string.equals("")) {
					continue;
				}
				try {
					player.getInventory().addItem(StreamSerializer.getDefault().deserializeItemStack(string));
				}
				catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
			setPlayerTime(player);
			return true;
		}
		return false;
	}

	public static boolean setItemsData(Inventory inventory)
	{
		String itemsData = createItemsData(inventory);
		String[] invTitles = inventory.getTitle().split("~");
		String sql;
		if (invTitles[1].equals("Common")) {
			sql = "UPDATE DRItems SET Items = '" + itemsData + "' WHERE Level = 0;";
		}
		else if (invTitles[1].equals("VIP")) {
			sql = "UPDATE DRItems SET Items = '" + itemsData + "' WHERE Level = 1;";
		}
		else {
			sql = "UPDATE DRItems SET Items = '" + itemsData + "' WHERE Player = '" + invTitles[2] + "';";
		}
		try {
			Statement statement = DRISQL.connection.createStatement();
			statement.executeUpdate(sql);
			statement.close();
			return true;
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
}
